#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#include <vector>
#include <functional>

using namespace std;

using func_t = function<void(void)>;
vector<func_t> funcs;

void PrintLog(){
    std::cout << "这个是一个日志例程" << std::endl;
}

void OperMysql(){
    std::cout << "这个是一个操作数据库的例程" << std::endl;
}

void CheckNet(){
    std::cout << "这个是一个检测网络状态的例程" << std::endl;
}

void LoadTask(){
    funcs.push_back(PrintLog);
    funcs.push_back(OperMysql);
    funcs.push_back(CheckNet);
}

void HandlerAllTask(){
    for(const auto& func:funcs)
        func();
}

void SetNonBlock(int fd){
    int f1 = fcntl(fd, F_GETFL);
    if(f1 < 0){
        cerr << "error string: " << strerror(errno) << "error code: " << errno << endl;
        return;
    }
    fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
}

int main(){
    char buffer[64];
    SetNonBlock(0);
    LoadTask();
    while(true){
        printf(">>> ");
        fflush(stdout);
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if(n > 0){
            buffer[n-1] = 0;//回车键
            cout << "echo# " << buffer << endl;
        }
        else if(n == 0){
            cout << "end file" << endl;
            break;
        }
        else{
            if(errno == EAGAIN || errno == EWOULDBLOCK){
                HandlerAllTask();
                sleep(1);
                cout << "data not ready" << endl;
                continue;
            }
            else if(errno == EINTR){
                continue;
            }
            else{
                cerr << "read errno? " << "error string: " << strerror(errno) << "error code: " << errno << endl;
                break;
            }
        }
    }
}